const app = getApp();
const WxParse = require('../../lib/wxParse/wxParse.js');
const util = require('../../utils/util.js');
const timer = require('../../utils/wxTimer.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
Page({
    data: {
        id: 0,
        goods: {},
        gallery: [],
        galleryImage: '',
        specificationList: [],
        attrGroup: [],
        productList: [],
        cartGoodsCount: 0,
        checkedSpecPrice: 0,
        number: 1,
        checkedSpecText: '',
        tmpSpecText: '请选择规格和数量',
        openAttr: false,
        soldout: false,
        disabled: '',
        alone_text: '单独购买',
        userId: 0,
        priceChecked: false,
        goodsNumber: 0,
        loading: 0,
        current: 0,
        showShareDialog:0,
        userInfo:{},
        autoplay:true,
        goodsImage: '',
    },
    hideDialog: function (e) {
        let that = this;
        that.setData({
            showShareDialog: false,
        });
    },
    shareTo:function(){
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            util.loginNow();
            return false;
        } else {
            this.setData({
                showShareDialog: !this.data.showShareDialog,
            });
        }
    },
    createShareImage: function () {
        let id = this.data.id;
        wx.navigateTo({
            url: '/pages/share/index?goodsid=' + id
        })
    },
    previewImage: function (e) {
        let current = e.currentTarget.dataset.src;
        let that = this;
        wx.previewImage({
            current: current, // 当前显示图片的http链接  
            urls: that.data.galleryImages // 需要预览的图片http链接列表  
        })
    },
    bindchange: function(e) {
        let current = e.detail.current;
        this.setData({
            current: current
        })
    },
    inputNumber(event) {
        let number = event.detail.value;
        this.setData({
            number: number
        });
    },
    goIndex: function() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    onShareAppMessage: function(res) {
        let id = this.data.id;
        let name = this.data.goods.name;
        let image = this.data.goods.list_pic_url;
        let userId = this.data.userId;
        return {
            title: name,
            path: '/pages/goods/goods?id=' + id + '&&userId=' + userId,
            imageUrl: image
        }
    },
    setFootprint: function () {
        let token = wx.getStorageSync('token');
        if (token) {
            util.request(api.SaveFootprint, {goods_id: this.data.id, token: token}, 'POST').then(function (res) {})
        }
    },
    onUnload: function() {

    },
    handleTap: function(event) { //阻止冒泡 
    },
    getGoodsInfo: function() {
        let that = this;
        util.request(api.GoodsDetail, {
            id: that.data.id
        }).then(function(res) {
            if (res.code == 0) {
                let attr = res.data.attr_group;
                let _specificationList = res.data.specificationList;
                let arr = new Array();
                let checkedSpec = '';
                for (let i = 0; i < attr.length; i++) {
                    for (let j = 0; j < attr[i].attr_list.length; j++) {
                        if (attr[i].attr_list[j].checked) {
                            arr.push(attr[i].attr_list[j].attr_id);
                            checkedSpec += '+' + attr[i].attr_list[j].attr_name;
                        }
                    }
                }
                let str = arr.join(':');
                let spec= {};
                for (let u = 0; u < _specificationList.length; u++) {
                    if (_specificationList[u].sign_id == str) {
                        spec = _specificationList[u];
                    }
                }
                checkedSpec = checkedSpec.substr(1);
                that.setData({
                    goodsImage: spec.pic_url ? spec.pic_url : res.data.info.pic_url,
                    checkedSpecText: '已选择：' + checkedSpec,
                    checkedSpecPrice: spec.price,
                    priceChecked: true
                });
                that.setData({
                    goods: res.data.info,
                    goodsNumber: spec.stock,
                    gallery: res.data.gallery,
                    specificationList: res.data.specificationList,
                    attrGroup: attr,
                //     productList: res.data.productList,
                    checkedSpecPrice: res.data.info.retail_price,
                    loading:1
                });
                WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, that);
                // wx.setStorageSync('goodsImage', res.data.info.https_pic_url);
            }
            else{
                util.showErrorToast(res.msg)
            }
        });
    },
    clickSkuValue: function(event) {
        let attrGroup = this.data.attrGroup;
        let _specificationList = this.data.specificationList;
        let specValueId = event.currentTarget.dataset.valueId;
        let index = event.currentTarget.dataset.index;
        let arr = new Array();
        for (let i = 0; i < attrGroup.length; i++) {
            for (let j = 0; j < attrGroup[i].attr_list.length; j++) {
                if (attrGroup[i].attr_list[j].checked) {
                    arr.push(attrGroup[i].attr_list[j].attr_id);
                }
            }
        }
        for (let t = 0; t < arr.length; t++) {
            if (index == t) {
                arr[t] = specValueId;
            }
        }
        // 对比查找特定信息
        let str = arr.join(':');
        let list = attrGroup[index].attr_list;
        for (let i = 0; i < list.length; i++) {
            if (list[i].attr_id == specValueId) {
                list[i].checked = true;
            } else {
                list[i].checked = false;
            }
        }
        attrGroup[index].attr_list = list;
        let spec= {};
        for (let u = 0; u < _specificationList.length; u++) {
            if (_specificationList[u].sign_id == str) {
                spec = _specificationList[u];
            }
        }
        let pic_url = '';
        if (spec.pic_url) {
            pic_url = spec.pic_url;
        } else {
            pic_url = this.data.goods.pic_url;
        }
        if (spec.stock <= 0) {
            wx.showToast({
                image: '/images/icon/icon_error.png',
                title: '规格库存不足',
            });
            return;
        }
        this.setData({
            attrGroup: attrGroup,
            goodsNumber: spec.stock,
            goodsImage: pic_url,
            checkedSpecPrice: spec.price,
            priceChecked: true
        });
    },
    // 获取选中的规格信息
    getCheckedSpecValue: function() {
        let checkedValues = [];
        let _attr = this.data.attrGroup;
        let _checkedObj = {
            valueId: 0,
            valueText: ''
        };
        let arr = new Array();
        let checkedSpec = '';
        for (let i = 0; i < _attr.length; i++) {
            for (let j = 0; j < _attr[i].attr_list.length; j++) {
                if (_attr[i].attr_list[j].checked) {
                    arr.push(_attr[i].attr_list[j].attr_id);
                    checkedSpec += '+' + _attr[i].attr_list[j].attr_name;
                }
            }
        }
        let str = arr.join(':');
        _checkedObj.valueId = str;
        _checkedObj.valueText = checkedSpec.substr(1);
        checkedValues.push(_checkedObj);
        return checkedValues;
    },
    // 根据已选的值，计算其它值的状态
    setSpecValueStatus: function() {

    },
    // 判断规格是否选择完整
    isCheckedAllSpec: function() {
        return !this.getCheckedSpecValue().some(function(v) {
            if (v.valueId == 0) {
                return true;
            }
        });
    },
    getCheckedSpecKey: function() {
        let checkedValue = this.getCheckedSpecValue().map(function(v) {
            return v.valueId;
        });
        return checkedValue;
    },
    onLoad: function(options) {
        let id = 0;
        var scene = decodeURIComponent(options.scene);
        if (scene != 'undefined') {
            id = scene;
        } else {
            id = options.id;
        }
        this.setData({
            id: id, // 这个是商品id
            valueId: id,
        });
        this.setFootprint();
    },
    onShow: function() {
        let userInfo = wx.getStorageSync('userInfo');
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 100;
        let userId = userInfo.id;
        if (userId > 0) {
            this.setData({
                userId: userId,
                userInfo: userInfo,
            });
        }
        this.setData({
            priceChecked: false,
            sysHeight: sysHeight
        });
        this.getGoodsInfo();
        this.getCartCount();
    },
    onHide:function(){
        this.setData({
            autoplay:false
        })
    },
    getCartCount: function() {
        let that = this;
        let token = wx.getStorageSync('token');
        util.request(api.CartGoodsCount, {token: token}, "POST").then(function(res) {
            if (res.code == 0) {
                if (res.data > 0) {
                    that.setData({
                        cartGoodsCount: res.data
                    });
                }
            }
        });
    },
    onPullDownRefresh: function() {
        wx.showNavigationBarLoading();
        this.getGoodsInfo();
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
    openCartPage: function() {
        wx.switchTab({
            url: '/pages/cart/cart',
        });
    },
    goIndexPage: function() {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    switchAttrPop: function() {
        if (this.data.openAttr == false) {
            this.setData({
                openAttr: !this.data.openAttr
            });
        }
    },
    closeAttr: function() {
        this.setData({
            openAttr: false,
            alone_text: '单独购买'
        });
    },
    goMarketing: function(e) {
        let that = this;
        that.setData({
            showDialog: !this.data.showDialog
        });
    },
    addToCart: function() {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        let that = this;
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        let checkedSpecKey = this.getCheckedSpecKey();
        if (this.data.openAttr == false) {
            //打开规格选择窗口
            this.setData({
                openAttr: !that.data.openAttr
            });
            this.setData({
                alone_text: '加入购物车'
            })
        } else {
            // 提示选择完整规格
            if (!this.isCheckedAllSpec()) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '请选择规格',
                });
                return false;
            }
            // 根据选中的规格，判断是否有对应的sku信息
            let _specificationList = that.data.specificationList;
            let spec = {};
            for (let u = 0; u < _specificationList.length; u++) {
                if (_specificationList[u].sign_id == checkedSpecKey[0]) {
                    spec = _specificationList[u];
                }
            }
            // 验证库存
            if (spec.stock <= 0) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            if (spec.stock < this.data.number) {
                // 要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let token = wx.getStorageSync('token');
            util.request(api.CartAdd, {
                sign: 0,
                token: token,
                goods_id: this.data.id,
                attr_id: spec.id,
                number: this.data.number,
            }, "POST").then(function (res) {
                let _res = res;
                if (_res.code == 0) {
                    wx.showToast({
                        title: '添加成功',
                    });
                    if (that.data.openAttr == true) {
                        that.setData({
                            openAttr: !that.data.openAttr,
                            cartGoodsCount: _res.data.goods_count
                        });
                    } else {
                        that.setData({
                            cartGoodsCount: _res.data.goods_count
                        });
                    }
                } else {
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: _res.msg,
                    });
                }

            });
        }
    },
    fastToCart: function() {
        // 判断是否登录，如果没有登录，则登录
        util.loginNow();
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo == '') {
            return false;
        }
        let that = this;
        let checkedSpecKey = this.getCheckedSpecKey();
        if (this.data.openAttr === false) {
            // 打开规格选择窗口
            this.setData({
                openAttr: !this.data.openAttr
            });
            that.setData({
                alone_text: '加入购物车'
            })
        } else {
            // 提示选择完整规格
            if (!this.isCheckedAllSpec()) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '请选择规格',
                });
                return false;
            }
            // 根据选中的规格，判断是否有对应的sku信息
            let _specificationList = that.data.specificationList;
            let spec = {};
            for (let u = 0; u < _specificationList.length; u++) {
                if (_specificationList[u].sign_id == checkedSpecKey[0]) {
                    spec = _specificationList[u];
                }
            }
            if (spec.stock <= 0) {
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            if (spec.stock < this.data.number) {
                // 要买的数量比库存多
                wx.showToast({
                    image: '/images/icon/icon_error.png',
                    title: '库存不足',
                });
                return false;
            }
            let token = wx.getStorageSync('token');
            // 添加到购物车
            util.request(api.CartAdd, {
                sign: 1,
                token: token,
                goods_id: this.data.id,
                attr_id: spec.id,
                number: this.data.number,
            }, "POST").then(function(res) {
                let _res = res;
                if (_res.code == 0) {
                    let id = res.data.id;
                    wx.navigateTo({
                        url: '/pages/order-check/index?sign=1&cart_id=' + id
                    });
                } else {
                    wx.showToast({
                        image: '/images/icon/icon_error.png',
                        title: _res.errmsg,
                    });
                }
            });
        }
    },
    cutNumber: function() {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
        this.setData({
            disabled: ''
        });
    },
    addNumber: function() {
        this.setData({
            number: Number(this.data.number) + 1
        });
        let _specificationList = this.data.specificationList;
        let checkedSpecKey = this.getCheckedSpecKey();
        let spec = {};
        for (let u = 0; u < _specificationList.length; u++) {
            if (_specificationList[u].sign_id == checkedSpecKey[0]) {
                spec = _specificationList[u];
            }
        }
        if (this.data.number >= spec.stock) {
            this.setData({
                disabled: true
            })
        }
    }
})